package com.guapi.mapper.wrapper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guapi.exception.SelfException;

import java.lang.reflect.Field;
import java.util.HashMap;

public class SelfQueryWrapper<T> extends QueryWrapper<T> {
    public SelfQueryWrapper(T entity) {
        Field[] fields = entity.getClass().getDeclaredFields();
        HashMap<String, Object> map = new HashMap<>();
        try {
            Class<?> superclass = entity.getClass().getSuperclass();
            Field idField = null;
            if (superclass == null || superclass.isInstance(Object.class)) {
                idField = entity.getClass().getDeclaredField("id");
            } else {
                idField = superclass.getDeclaredField("id");
            }
            idField.setAccessible(true);
            Object idValue = idField.get(entity);
            if (idValue != null) {
                map.put(idField.getName(), idValue);
            }
            for (Field field : fields) {
                field.setAccessible(true);

                TableField annotation = field.getAnnotation(TableField.class);
                if (annotation != null) {
                    if (!annotation.exist()) {
                        continue;
                    }
                    if (ObjectUtil.isAllNotEmpty(annotation.value(), field.get(entity))) {
                        map.put(annotation.value(), field.get(entity));
                    }
                } else {
                    if (ObjectUtil.isNotEmpty(field.get(entity))) {
                        map.put(field.getName(), field.get(entity));
                    }
                }
            }
            if (map.size() == 0) {
                throw new IllegalAccessException();
            }
            this.allEq(map);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new SelfException("找不到命名域", e);
        } catch (IllegalAccessException e) {
            throw new SelfException("不能传入空对象,请检查输入对象", e);
        }
    }

    public SelfQueryWrapper() {
        super();
    }
}
